﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.DBUtility;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace H2.NET.Web.Pages.SMD
{
    public partial class ChangeStore : BasePage
    {
        public IList<t_StoreDataChangeLog> logs = new List<t_StoreDataChangeLog>();
        private int storeid = 0;
        public string contractStartDate = "";
        public string subdealerCallBack { get; set; }
        public string bmcCallBack { get; set; }
        public string accountownerCallBack { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {

            //判断数据库内是否存在此门店名称
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
            //string sql = "select * from t_smd_Store where StoreName like '%" + AksRequest.GetFormString("tb_store_name") + "%'";
            //Logging.GetLogger().Info(sql);
            //DataTable dt_storeName = DbHelperSQL.Query(sql).Tables[0];
            //if (dt_storeName.Rows.Count > 1)
            //{
            //    string returnMsg = "该门店名称已存在！请重新核对！";
            //    returnMsg = string.IsNullOrEmpty(returnMsg) ? Resources.Global.C_00_Failed : returnMsg;
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
            //}

            #region 选择负责销售 Add By Tony 20160607
            Dictionary<string, string> accountownerDic = new Dictionary<string, string>();

            accountownerDic.Add(tb_accountowner.ClientID, "AccountOwner");
            accountownerDic.Add(h_windowsid.ClientID, "WindowsId");
            uc_search_accountowner1.accountownerDic = accountownerDic;
            uc_search_accountowner1.accountownerCallBack = accountownerCallBack;
            #endregion

            #region 选择建材市场 Add By Tony 20160607
            Dictionary<string, string> bmcDic = new Dictionary<string, string>();

            bmcDic.Add(bmccode.ClientID, "BMCCode");
            bmcDic.Add(l_bmcname.ClientID, "BMCName");
            uc_search_bmc1.bmcDic = bmcDic;
            uc_search_bmc1.bmcCallBack = bmcCallBack;
            #endregion

            #region 选择分销商-- Add By Tony 20160607

            if (cb_ownertype.Checked == false)
            {
                subdealercode.Style.Add("Display", "none");
            }
            else
            {
                subdealercode.Style.Add("Display", "inline");
            }

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add(subdealer_id.ClientID, "SubDealerID");
            dic.Add(subdealercode.ClientID, "SubDealerCode");
            dic.Add(l_subdealername.ClientID, "SubDealerName");
            uc_search_subdealer1.dic = dic;
            uc_search_subdealer1.subdealerCallBack = subdealerCallBack;
            #endregion

            DwzAssessment1.Category = "ChangeStore";
            uc_dealer1.IsCanEditAuthID = false;
            storeid = TaskAPI.GetStoreId("storeid");
            string key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            if (key == Constant.PROCESS_STORE)
            {
                tr_storeDowngrad.Visible = false;
            }
            else if (key == Constant.PROCESS_CHANGELEVEL)
            {
                tr_storeRenew.Visible = false;
                tr_storeUpgrad.Visible = false;
            }

            if (!IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }

                if (key.Equals(Constant.PROCESS_STORE))
                {
                    var contract = ContractService.GetContractByStoreID(storeid);
                    if (contract != null && contract.StoreContractBeginDate.HasValue)
                    {
                        contractStartDate = contract.StoreContractBeginDate.Value.ToString("yyyy-MM-dd");
                    }
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                InitDropDownList();

                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);

                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    // 如果有值，说明是退回来的
                    var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    assessment.Visible = false;
                    if (!string.IsNullOrEmpty(blankVlue))
                    {
                        tb_authId.CssClass = "readonly";
                        tb_authId.Attributes.Remove("onclick");
                    }

                    if (storeid > 0)
                    {
                        var store = (t_smd_Store._StoreID == storeid).ListFirst<t_smd_Store>(Storage.Context3);
                        if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                        {
                            var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                            /*Egbert-取出ShortName 这条数据--2016-11-22*/
                            var logshortname = changelogs.Where(s => s.FieldName == "ShortName").ToList();
                            /*Egbert-去除ShortName 这条数据--2016-11-22*/
                            changelogs = changelogs.Where(c => c.FieldName != "ShortName").ToList();



                            uc_dealer1.IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;

                            if (store != null)
                                store = DataHelper<t_smd_Store>.Reload(store, changelogs);
                            assessment.Visible = true;
                        }
                        BindControl(store, true);
                        var dealer = DealerService.GetById(store.DealerID.Value);
                        uc_dealer1.dealer = dealer;
                        uc_dealer1.store = store;
                        /*Egbert-显示ShortName门店昵称--2016-11-22*/
                        //uc_dealer1.IsShortName = store.DealerShortName;
                        uc_dealer1.IsShortNameHasValue = false;
                        //uc_dealer1.IsCanAuthID = false;
                        
                       
                            

                    }
                }
                #endregion

                #region Data Check 、Manager Approve
                else if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                {

                    tb_changelogs.Visible = true;
                    uc_change_field1.AssessmentIDs = assIds;
                    tb_authId.CssClass = "readonly";
                    tb_authId.Attributes.Remove("onclick");

                    var changelogs = ChangeLogService.GetLastChangeLogs(assIds);


                    /*Egbert-取出ShortName门店昵称 这条数据--2016-11-22*/
                    var logshortname = changelogs.Where(s => s.FieldName == "ShortName").ToList();
                    /*Egbert-去除ShortName门店昵称 这条数据--2016-11-22*/
                    changelogs = changelogs.Where(c => c.FieldName != "ShortName").ToList();
                  

                    var store = StoreService.GetSmdStoreById(storeid);
                    t_smd_Dealer dealer = DealerService.GetById(store.DealerID.Value);
                    uc_dealer1.dealer = dealer;
                    /*Egbert-显示ShortName门店昵称--2016-11-22*/
                    uc_dealer1.IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;
                    
                    logs = changelogs;
                    store = DataHelper<t_smd_Store>.Reload(store, changelogs);
                    uc_dealer1.IsStillDealer = false;
                    Logging.GetLogger().Debug(uc_dealer1.IsShortName); 
                    BindControl(store, true);
                    //Chris wang经销商简称
                    //uc_dealer1.IsStillDealer = false;
                   
                }
                #endregion

                #region DMO Commite
                else
                {
                    #region 加载数据并显示
                    // 门店数据
                    var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    var store = StoreService.GetSmdStoreById(storeid);
                    t_smd_Dealer dealer = DealerService.GetById(store.DealerID.Value);
                    uc_dealer1.dealer = dealer;
                    logs = (t_StoreDataChangeLog._AssessmentID.In(assIds)).List<t_StoreDataChangeLog>();

                    /*Egbert-取出ShortName门店昵称 这条数据--2016-11-22*/
                    var logshortname = logs.Where(s => s.FieldName == "ShortName").ToList();
                    /*Egbert-去除ShortName门店昵称 这条数据--2016-11-22*/
                    logs = logs.Where(c => c.FieldName != "ShortName").ToList();

                    /*Egbert-显示ShortName门店昵称--2016-11-22*/
                    uc_dealer1.IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;

                    /*修改数据把经销商简称修改到数据库*/
                    //dealer.DealerID


                    store = DataHelper<t_smd_Store>.Reload(store, logs.ToList());
                    uc_change_field1.AssessmentIDs = assIds;
                    tb_changelogs.Visible = true;
                    uc_dealer1.IsDMODealer = false;
                    BindControl(store, false);

                    tb_LastRenewDate.Visible = false;
                    #endregion

                    #region 审批项初始化
                    switch (TaskAPI.Step)
                    {
                        case "Manager Approve":
                            break;
                        case "DMO Commit":
                            DwzAssessment1.Category = null;
                            break;
                    }
                    #endregion
                }
                #endregion
            }
        }

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                tb_changelogs.Visible = true;
                btn_submit.Visible = false;
                DwzAssessment1.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;

                var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                if (storeMasterData == null)
                {
                    BindControlRead();
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);
                var dealer = DealerService.GetById(store.DealerID.Value);
                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);

                DataHelper<t_smd_Store>.Reload(store, logs.ToList());

                uc_dealer1.dealer = dealer;
                uc_change_field1.AssessmentIDs = assIds;
                var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                /*Egbert-取出ShortName 这条数据--2016-11-22*/
                var logshortname = changelogs.Where(s => s.FieldName == "ShortName").ToList();
                /*Egbert-去除ShortName 这条数据--2016-11-22*/
                changelogs = changelogs.Where(c => c.FieldName != "ShortName").ToList();

                store = DataHelper<t_smd_Store>.Reload(store, changelogs);

                /*Egbert-显示ShortName门店昵称--2016-11-22*/
                uc_dealer1.IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;

                assessment.Visible = true;
                BindControl(store, false);

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }

        #endregion

        private bool Send(ref string return_msg)
        {
            var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            bool flag = false;
            try
            {
                var _store = StoreService.GetSmdStoreById(storeid);
                var _dealer = DealerService.GetById(_store.DealerID.Value);

              
               


                #region 数据验证
                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                if (ddl_StoreStatus.Text != "营业" && TaskAPI.Step == "Submit Data" && key == Constant.PROCESS_STORE)
                {
                    return_msg = "请选择门店状态为营业";
                    return false;
                }
                if (_store.IsRenew != null && _store.IsRenew.Value && tb_LastRenewDate.Text == "" && TaskAPI.Step != "DMO Commit")
                {
                    return_msg = "请选择翻新日期";
                    return false;
                }
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {

                    //判断前5位是否存在[市]
                    Logging.GetLogger().Info(tb_store_name.Text.Trim() + _store.StoreType);
                    if ((_store.StoreType == "DCSS" || _store.StoreType == "DDCN") && !string.IsNullOrWhiteSpace(this.tb_store_name.Text.Trim()))
                    {
                        string store_name = this.tb_store_name.Text.Trim().Substring(0, 5);
                        if (store_name.IndexOf("市") < 0)
                        {
                            return_msg = "门店名称省市异常,请重新选择门店城市！";
                            return false;
                        }
                    }
                    //判断数据库内是否存在此门店名称
                    DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");

                    var storename = string.Empty;
                    string sql = "select * from t_smd_Store where StoreName like  '%" + this.tb_store_name.Text.Trim() + "%'";
                    Logging.GetLogger().Info(sql);
                    DataTable dt_storeName = DbHelperSQL.Query(sql).Tables[0];
                    if (dt_storeName.Rows.Count > 1)
                    {
                        return_msg = "该门店名称已存在！请重新核对！!";
                        return false;
                    }

                    if (storeid == 0)
                    {
                        return_msg = "请选择门店";
                        return false;
                    }

                    var storeids = StoreService.FindUnFinishStore(new List<int> { storeid });
                    if (storeids.Contains(storeid) && key != Constant.PROCESS_STORE)
                    {
                        return_msg = "对不起，该门店正处于新开门店流程中，不能发起门店变更";
                        return false;
                    }

                    if (cb_ShowInWebsite.Checked && !ajaxUpload1.IsHaveAttachment)
                    {
                        return_msg = "请提交DR2审批邮件";
                        return false;
                    }
                    var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
                    var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
                    var parentStoreMaster =
                    (t_StoreMasterData._Process == parentProcess & t_StoreMasterData._Incident == parentIncident)
                        .ListFirst<t_StoreMasterData>();
                    if ((parentStoreMaster != null && parentStoreMaster.NewFitment == "翻新") && tb_LastRenewDate.Text == "")
                    {
                        return_msg = "请填写最新翻新日期";
                        return false;
                    }

                    if (parentStoreMaster != null && (parentStoreMaster.NewFitment.Contains("升级") ||
                        parentStoreMaster.NewFitment.Contains("降级")))
                    {
                        if (_store.CurrentStartDate != null && (_store.StoreType == "DDCN" || _store.StoreType == "DCSS") && _store.CurrentStartDate.Value.ToString("yyyy-MM-dd") == tb_CurrentStartDate.Text)
                        {
                            return_msg = "升级或降级必须修改目前店面开业时间";
                            return false;
                        }
                    }

                }
                if (TaskAPI.IsAllowSubmit && TaskAPI.Step != "DMO Commit")
                {
                    var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
                    var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
                    var parentStoreMaster =
                   (t_StoreMasterData._Process == parentProcess & t_StoreMasterData._Incident == parentIncident)
                       .ListFirst<t_StoreMasterData>();
                     if ((parentStoreMaster != null && parentStoreMaster.NewFitment.Contains("升级")))
                     {
                    if (storeType.SelectedValue == ddl_BeforeUpgradedType.SelectedValue)
                    {
                        return_msg = "对不起，当前的门店类型与升级前的门店类型不能一致！";
                        return false;
                    }
                     }

                    if (string.IsNullOrEmpty(tb_lon.Text) || Convert.ToDecimal(tb_lon.Text) > 999)
                    {

                        return_msg = "对不起，经度格式不正确！";
                        return false;
                    }
                    if (string.IsNullOrEmpty(tb_lat.Text) || Convert.ToDecimal(tb_lat.Text) > 999)
                    {

                        return_msg = "对不起，纬度格式不正确！";
                        return false;
                    }
                }


                #endregion

                #region 引擎传值

                if (TaskAPI.Step == "Submit Data")
                {

                    // 空的话，是手动发起的流程
                    TaskAPI["BlankVlue"] = storeid;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "门店信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "门店信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;
                        else if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)提交门店信息变更/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;

                    }
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "门店信息DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;
                        else if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)门店信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;

                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        return_msg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;

                        assessment.Visible = true;

                        if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)门店信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID + "|" + _dealer.DealerCode;
                    }

                }


                #endregion

                #region 提交步骤

                string step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }
                    #endregion



                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        t_StoreMasterData storeMasterData = new t_StoreMasterData();
                        storeMasterData.SubmitDate = DateTime.Now;
                        storeMasterData.Creator = TaskAPI.UserName;
                        storeMasterData.ApplicationNO = uc_head1.applicationNo;
                        storeMasterData.Process = TaskAPI.Process;
                        storeMasterData.Incident = TaskAPI.Incident;
                        storeMasterData.StoreId = storeid;
                        storeMasterData.BusinessProcess = ass.BusinessProcess;
                        storeMasterData.BusinessKey = ass.BusinessKey;
                        Storage.Save(Storage.Context1, storeMasterData);

                        // 记录变更日志
                        var changelogs = SaveChangeLog(storeid, ass.ID);
                        if (changelogs.Count == 0)
                        {
                            throw new Exception("对不起，数据无任何修改，提交失败");
                        }
                        Storage.Save(Storage.Context1, changelogs.ToArray());

                        if (key.Equals(Constant.PROCESS_CHANGEOTHER))
                        {
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");

                            var store = StoreService.GetSmdStoreById(storeid);
                            var dealer = DealerService.GetById(store.DealerID.Value);

                            BusinessService.saveProcessRelation(TaskAPI, ass, store, null, dealer, null, null, null, null);

                            if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                            {
                                TaskAPI.Summary = "门店信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + "|" + _store.AuthID + "|" + _dealer.DealerCode;
                            }
                        }
                    }
                    #endregion

                    #region “Data Check”步骤
                    if (TaskAPI.Step == "Data Check")
                    {
                        var changelogs = SaveChangeLog(storeid, ass.ID);
                        Storage.Save(changelogs.ToArray());
                    }
                    #endregion

                    #region “Manager Approve”步骤
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            var changelogs = SaveChangeLog(storeid, ass.ID);
                            Storage.Save(changelogs.ToArray());
                        }
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            // 将变更日志转移至smd数据库
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            /*Egbert-取出数据出来 2016-12-6*/
                            var existingChangelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);
                            /*Egbert-取出ShortName 这条数据--2016-11-22*/
                            var logshortname = existingChangelogs.Where(s => s.FieldName == "ShortName").ToList();
                            var IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;

                            var id = smd_changelogs[0].DataID;// 获取业务数据主键
                            t_smd_Store store = StoreService.GetSmdStoreById(Utils.StrToInt(id, 0));// 获取原始门店数据
                            /*Egbert-去除ShortName 这条数据--2016-11-22*/
                            smd_changelogs = smd_changelogs.Where(c => c.FieldName != "ShortName").ToList();

                            t_smd_Dealer dealer = DealerService.GetById(store.DealerID.Value);

                            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");

                            int Execute = DbHelperSQL.ExecuteSql("update t_smd_Store  set DealerShortName=@ShortName where StoreID=@StoreID"
                                , new SqlParameter("@ShortName", IsShortName), new SqlParameter("@StoreID", store.StoreID));

                            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");

                            store = DataHelper<t_smd_Store>.Reload(store, smd_changelogs);// 根据变更日志重新加载门店信息
                            store.StoreReportStatus = "营业";
                            Storage.Save(Storage.Context3, store);// 更新门店信息

                            // 更新业务数据状态
                            StoreMasterDataService.UpdateFinish(TaskAPI);
                            step = "Finish";
                            BusinessService.saveProcessRelation(TaskAPI, ass, store, null, null, null, null, null, null);
                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");


                            #region Add By Tony 20160530
                            var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            #region add by zsz 2017/7/25
                            BusinessService.SaveSycnMappingOrBusinesskey("0","0", masterStore.BusinessKey);
                            #endregion
                            //var subdealer = DealerService.GetByCode(store.SubDealerCode == null ? "" : store.SubDealerCode);
                            //var devicer = DeviceService.GetOneByStoreId(store.StoreID);
                            //var deposit = DepositService.GetDepositByStoreId(store.StoreID);
                            //BusinessService.SaveCRMSyncData(masterStore, store, dealer, subdealer);
                            #endregion

                        }
                        else if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion

                    if (DwzAssessment1.Assessment.Opinion != "2")
                    {
                        // 变更列表
                        TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                        flag = TaskAPI.Send();
                    }

                    //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                    if (TaskAPI.Step == "Submit Data")
                    {
                        (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });

                        (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });
                    }
                    if (!flag) o.Rollback();
                });

                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用ChangeStore.aspx方法Send_Click出错：" + ex);
                Logging.GetLogger().Error(string.Format("{0}_{1}_{2}_{3}", TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step, ex.StackTrace));
                flag = false;
            }
            return flag;
        }

        #region 绑定各选项
        private void InitDropDownList()
        {
            var configService = new ConfigService();

            #region 门店类型
            DataTable dt_area = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_MDLX') order by seq").Tables[0];
            storeType.AppendDataBoundItems = true;
            storeType.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_area.Rows)
            {
                storeType.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }

            ddl_BeforeUpgradedType.AppendDataBoundItems = true;
            ddl_BeforeUpgradedType.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_area.Rows)
            {
                ddl_BeforeUpgradedType.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }

            ddl_BeforeDowngradedType.AppendDataBoundItems = true;
            ddl_BeforeDowngradedType.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_area.Rows)
            {
                ddl_BeforeDowngradedType.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }

            ddl_BeforeRenewType.AppendDataBoundItems = true;
            ddl_BeforeRenewType.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_area.Rows)
            {
                ddl_BeforeRenewType.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }
            #endregion

            #region 渠道
            DataTable dt_channel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_QD') order by seq").Tables[0];
            ddl_channel.AppendDataBoundItems = true;
            ddl_channel.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_channel.Rows)
            {
                ddl_channel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 城市类型
            DataTable dt_cityClass = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_CSLX') order by seq").Tables[0];

            #endregion

            #region 门店状态
            DataTable dt_storeStatus = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_MDZT') order by seq").Tables[0];
            ddl_StoreStatus.AppendDataBoundItems = true;
            ddl_StoreStatus.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_storeStatus.Rows)
            {
                ddl_StoreStatus.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 店序号
            ddl_ShopSeq.AppendDataBoundItems = true;
            ddl_ShopSeq.Items.Add(new ListItem("无", ""));
            for (int i = 1; i < 11; i++)
            {
                ddl_ShopSeq.Items.Add(new ListItem(i + "店", i + "店"));
            }
            #endregion

            #region 门店装修类型
            DataTable dt_NewFitment = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_NewFitme') order by seq").Tables[0];
            ddl_NewFitment.AppendDataBoundItems = true;
            ddl_NewFitment.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_NewFitment.Rows)
            {
                ddl_NewFitment.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

        }
        #endregion

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string returnMsg = string.Empty;
            if (Send(ref returnMsg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                return;
            }
            else
            {
                returnMsg = string.IsNullOrEmpty(returnMsg) ? Resources.Global.C_00_Failed : returnMsg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
                return;
            }
        }

        private void BindControl(t_smd_Store store, bool isEdit)
        {
            #region Add By Tony 20160525
            var subdealer = new t_smd_Dealer();
            if (!string.IsNullOrEmpty(store.SubDealerCode))
            {
                subdealer = DealerService.GetByCode(store.SubDealerCode);
            }


            var bmc = new t_smd_BMCInfo();
            if (!string.IsNullOrEmpty(store.BMCCode))
            {
                bmc = BMCService.GetByCode(store.BMCCode);
            }

            var accountOwner = new t_smd_AccountOwner();
            if (!string.IsNullOrEmpty(store.AccountOwner))
            {
                accountOwner = AccountOwnerService.GetById(store.AccountOwner);
            }

            #endregion


            l_CMS.Text = store.AccountCMS;

            if (isEdit)
            {

                #region 门店城市
                if (store != null)
                {
                    DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
                    DataTable dt_cityName = DbHelperSQL.Query("select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" + store.Province + "' and level =2) order by seq asc").Tables[0];
                    ddl_cityName.AppendDataBoundItems = true;
                    foreach (DataRow row in dt_cityName.Rows)
                    {
                        ddl_cityName.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                    }
                }
                #endregion

                var storeTypeCode = StoreService.GetStoreTypeCode(store.StoreType);
                //tb_LastRenewDate.Visible = false;
                ddl_NewFitment.Visible = false;
                ddl_channel.SelectedValue = store.Channel;
                ddl_cityName.SelectedValue = store.CityName;//chris wang 新增
                tb_LastRenewDate.Text = store.LastRenewDate == null ? "" : store.LastRenewDate.Value.ToString("yyyy-MM-dd");
                cb_IsTintingService.Checked = store.IsTintingService.HasValue && store.IsTintingService.Value;
                cb_IsColourService.Checked = store.IsColourService.HasValue && store.IsColourService.Value;
                tb_authId.Text = store.AuthID;
                tb_store_name.Text = store.StoreName;
                // DDNC、DCSS类型的门店手动发起的不能修改门店状态
                if ((storeTypeCode == "DDCN" || storeTypeCode == "DCSS")
                    && string.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("ParentIncident")))
                {
                    l_StoreStatus.Text = store.StoreStatus;
                    ddl_StoreStatus.Style.Value = "display:none";
                }
                tb_store_name.Attributes.Add("readonly", "readonly");
                string key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                if (storeTypeCode != "DDCN" && storeTypeCode != "DCSS"
                    && key != "")
                {
                    tb_CurrentStartDate.Visible = false;
                }

                ddl_StoreStatus.SelectedValue = store.StoreStatus;
                storeType.SelectedValue = storeTypeCode;

                // 升级，可以选择门店类型
                if (store.NewFitment.Contains("升级"))
                {
                    storeType.Style.Value = "";
                }
                else
                {
                    l_storeType.Text = StoreService.GetStoreType(store.StoreType);
                }
                //uc_dealer1.IsShortName = store.DealerShortName;
                tb_ContractPerson.Text = store.ContactPerson;
                tb_Telephone.Text = store.PhoneNumber;
                tb_StoreSize.Text = Utils.ObjectToStr(store.StoreSize);
                if (store.ShowInWebsite != null)
                    cb_ShowInWebsite.Checked = store.ShowInWebsite.Value;
                ddl_BeforeRenewType.SelectedValue = store.BeforeRenewType;
                tb_region.Text = store.Region;
                tb_province.Text = store.Province;
                ddl_cityName.SelectedValue = store.CityName;
                tb_address.Text = Distinct(store.StoreAddress);
                tb_lon.Text = store.Lon == null ? "" : store.Lon.Value.ToString();
                tb_lat.Text = store.Lat == null ? "" : store.Lat.Value.ToString();
                //ddl_NewFitment.SelectedValue = store.NewFitment;
                l_NewFitment.Text = store.NewFitment;

                #region Add By Tony 20160525
                cb_ownertype.Checked = string.IsNullOrEmpty(store.SubDealerCode) ? false : true;

                if (!cb_ownertype.Checked)
                {
                    subdealercode.Style.Add("display", "none");
                }
                else
                {
                    subdealercode.Style.Add("display", "inline");
                    subdealercode.Text = string.IsNullOrEmpty(subdealer.DealerCode) ? "" : subdealer.DealerCode;
                    l_subdealername.Text = string.IsNullOrEmpty(subdealer.Name) ? "" : subdealer.Name;
                }


                //if (!string.IsNullOrEmpty(store.BMCCode))
                //{
                //    if (bmc != null)
                //    {
                //        bmccode.Text = bmc.BMCCode;
                //        l_bmcname.Text = bmc.BMCName;
                //    }
                //}

                bmccode.Text = bmc.BMCCode == null ? "" : bmc.BMCCode;
                l_bmcname.Text = bmc.BMCName == null ? "" : bmc.BMCName;
                tb_accountowner.Text = accountOwner.AccountOwner == null ? "" : accountOwner.AccountOwner;
                tb_wechatid.Text = store.WechatId == null ? "" : store.WechatId;
                tb_District.Text = store.District == null ? "" : store.District;

                #endregion

                cb_IsUpgraded.Enabled = false;
                cb_IsDowngraded.Enabled = false;
                cb_IsRenew.Enabled = false;

                var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
                var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
                var parentStoreMaster =
                    (t_StoreMasterData._Process == parentProcess & t_StoreMasterData._Incident == parentIncident)
                        .ListFirst<t_StoreMasterData>();

                //Modified By Tony 20160503
                tb_CurrentStartDate.Enabled = (parentStoreMaster != null && store.NewFitment != "翻新");

                #region 翻新
                if ((parentStoreMaster != null && parentStoreMaster.NewFitment == "翻新"))
                {
                    cb_IsRenew.Checked = true;
                    tb_LastRenewDate.Visible = true;
                    ddl_BeforeRenewType.SelectedValue = string.IsNullOrEmpty(store.BeforeRenewType) ? store.StoreType : StoreService.GetStoreTypeCode(store.BeforeRenewType);
                    l_BeforeRenewType.Text = string.IsNullOrEmpty(store.BeforeRenewType) ? store.StoreType : StoreService.GetStoreTypeCode(store.BeforeRenewType);
                }
                else if ((store.IsRenew != null && store.IsRenew.Value))
                {
                    cb_IsRenew.Checked = store.IsRenew.Value;
                    l_LastRenewDate.Text = store.LastRenewDate == null ? "" : store.LastRenewDate.Value.ToString("yyyy-MM-dd");
                    ddl_BeforeRenewType.SelectedValue = string.IsNullOrEmpty(store.BeforeRenewType) ? store.StoreType : StoreService.GetStoreTypeCode(store.BeforeRenewType);
                    l_BeforeRenewType.Text = string.IsNullOrEmpty(store.BeforeRenewType) ? store.StoreType : StoreService.GetStoreTypeCode(store.BeforeRenewType);

                }

                #endregion

                #region 升级
                if ((parentStoreMaster != null && parentStoreMaster.NewFitment.Contains("升级")) || store.IsUpgraded != null && store.IsUpgraded.Value)
                {
                    cb_IsUpgraded.Checked = true;
                    //ddl_BeforeUpgradedType.Visible = false;
                    ddl_BeforeUpgradedType.SelectedValue = store.BeforeUpgradedType == null ? "" : StoreService.GetStoreTypeCode(store.BeforeUpgradedType);
                    l_BeforeUpgradedType.Text = store.BeforeUpgradedType == null ? "" : StoreService.GetStoreTypeCode(store.BeforeUpgradedType);
                }
                #endregion

                #region 降级
                if (store.IsDowngraded != null && store.IsDowngraded.Value)
                {
                    cb_IsDowngraded.Checked = true;
                    ddl_BeforeDowngradedType.Visible = false;
                    ddl_BeforeDowngradedType.SelectedValue = store.BeforeDowngradedType == null ? "" : StoreService.GetStoreTypeCode(store.BeforeDowngradedType);
                    l_BeforeDowngradedType.Text = store.BeforeDowngradedType == null ? "" : StoreService.GetStoreTypeCode(store.BeforeDowngradedType);

                }
                #endregion
                tb_OpenBusinessDate.Text = store.OpenBusinessDate == null ? "" : store.OpenBusinessDate.Value.ToString("yyyy-MM-dd");
                tb_MallShortName.Text = store.MallShortName;
                tb_MallName.Text = store.MallName;
                tb_HouseNumber.Text = store.HouseNumber;
                ddl_ShopSeq.SelectedValue = store.ShopSeq;

                FirstStartDate.Text = store.FirstStartDate == null ? "" : store.FirstStartDate.Value.ToString("yyyy-MM-dd");
                tb_CurrentStartDate.Text = store.CurrentStartDate == null ? "" : store.CurrentStartDate.Value.ToString("yyyy-MM-dd");
                tb_StoreApprovedDate.Text = store.StoreApprovedDate == null ? "" : store.StoreApprovedDate.Value.ToString("yyyy-MM-dd");
                tb_EapproveSN.Text = store.EapproveSN;
            }
            else
            {
                BindControlRead();

                l_channel.Text = store.Channel;
                l_NewFitment.Text = store.NewFitment;
                l_LastRenewDate.Text = store.LastRenewDate == null ? "" : store.LastRenewDate.Value.ToString("yyyy-MM-dd");
                cb_IsTintingService.Checked = store.IsTintingService.HasValue && store.IsTintingService.Value;
                cb_IsColourService.Checked = store.IsColourService.HasValue && store.IsColourService.Value;
                l_authId.Text = store.AuthID;
                l_StoreStatus.Text = store.StoreStatus;
                l_storeType.Text = StoreService.GetStoreType(store.StoreType);
                l_ContractPerson.Text = store.ContactPerson;
                l_Telephone.Text = store.PhoneNumber;
                l_StoreSize.Text = Utils.ObjectToStr(store.StoreSize);
                if (store.ShowInWebsite != null)
                    cb_ShowInWebsite.Checked = store.ShowInWebsite.Value;
                l_BeforeRenewType.Text = store.BeforeRenewType;
                l_region.Text = store.Region;
                l_province.Text = store.Province;
                l_province.Text = store.Province;
                l_address.Text = store.StoreAddress;
                l_lon.Text = (store.Lon ?? 0).ToString();
                l_lat.Text = (store.Lat ?? 0).ToString();
                l_store_name.Text = store.StoreName;
                if (store.IsUpgraded != null && store.IsUpgraded.Value)
                {
                    cb_IsUpgraded.Checked = true;
                }

                if (store.IsDowngraded != null && store.IsDowngraded.Value)
                {
                    cb_IsDowngraded.Checked = true;
                }

                if (store.IsRenew != null && store.IsRenew.Value)
                {
                    cb_IsRenew.Checked = true;

                }
                l_BeforeUpgradedType.Text = store.BeforeUpgradedType;
                l_BeforeRenewType.Text = store.BeforeRenewType;
                l_BeforeDowngradedType.Text = store.BeforeDowngradedType;
                l_FirstStartDate.Text = store.FirstStartDate == null ? "" : store.FirstStartDate.Value.ToString("yyyy-MM-dd");
                l_CurrentStartDate.Text = store.CurrentStartDate == null ? "" : store.CurrentStartDate.Value.ToString("yyyy-MM-dd");
                l_StoreApprovedDate.Text = store.StoreApprovedDate == null ? "" : store.StoreApprovedDate.Value.ToString("yyyy-MM-dd");
                l_EapproveSN.Text = store.EapproveSN;
                l_cityName.Text = store.CityName;
                l_OpenBusinessDate.Text = store.OpenBusinessDate == null ? "" : store.OpenBusinessDate.Value.ToString("yyyy-MM-dd");
                l_OpenBusinessDate.Text = store.OpenBusinessDate == null ? "" : store.OpenBusinessDate.Value.ToString("yyyy-MM-dd");
                l_MallShortName.Text = store.MallShortName;
                l_MallName.Text = store.MallName;
                l_HouseNumber.Text = store.HouseNumber;
                l_ShopSeq.Text = store.ShopSeq;

                #region Add By Tony 20160525

                cb_ownertype.Checked = string.IsNullOrEmpty(store.SubDealerCode) ? false : true;

                l_subdealercode.Text = string.IsNullOrEmpty(subdealer.DealerCode) ? "" : subdealer.DealerCode;
                l_subdealername.Text = string.IsNullOrEmpty(subdealer.Name) ? "" : subdealer.Name;


                l_bmccode.Text = bmc.BMCCode == null ? "" : bmc.BMCCode;
                l_bmcname.Text = bmc.BMCName == null ? "" : bmc.BMCName;

                if (string.IsNullOrEmpty(accountOwner.AccountOwner))
                {
                    l_accountowner.Text = "";
                }
                else
                {
                    l_accountowner.Text = accountOwner.AccountOwner;
                }


                l_wechatid.Text = store.WechatId == null ? "" : store.WechatId;
                l_District.Text = store.District == null ? "" : store.District;


                #endregion
            }
        }

        private void BindControlRead()
        {
            ddl_channel.Visible = false;
            ddl_NewFitment.Visible = false;
            //tb_LastRenewDate.Visible = false;
            cb_IsTintingService.Enabled = false;
            cb_IsColourService.Enabled = false;
            tb_authId.Visible = false;
            tb_store_name.Visible = false;
            ddl_StoreStatus.Visible = false;
            storeType.Visible = false;
            tb_ContractPerson.Visible = false;
            tb_Telephone.Visible = false;
            tb_StoreSize.Visible = false;
            cb_ShowInWebsite.Enabled = false;
            ddl_BeforeRenewType.Visible = false;
            tb_region.Visible = false;
            tb_province.Visible = false;
            ddl_cityName.Visible = false;
            tb_address.Visible = false;
            tb_lon.Visible = false;
            tb_lat.Visible = false;
            cb_IsUpgraded.Enabled = false;
            cb_IsDowngraded.Enabled = false;
            cb_IsRenew.Enabled = false;
            ddl_BeforeUpgradedType.Visible = false;
            ddl_BeforeRenewType.Visible = false;
            ddl_BeforeDowngradedType.Visible = false;
            FirstStartDate.Visible = false;
            tb_CurrentStartDate.Visible = false;
            tb_StoreApprovedDate.Visible = false;
            tb_EapproveSN.Visible = false;
            ddl_cityName.Visible = false;
            tb_OpenBusinessDate.Visible = false;
            tb_OpenBusinessDate.Visible = false;
            tb_MallShortName.Visible = false;
            tb_MallName.Visible = false;
            tb_HouseNumber.Visible = false;
            ddl_ShopSeq.Visible = false;

            #region Add By Tony 20160525
            cb_ownertype.Enabled = false;
            subdealercode.Visible = false;
            bmccode.Visible = false;
            //l_bmcname.Visible = false;
            tb_accountowner.Visible = false;
            tb_wechatid.Visible = false;
            tb_District.Visible = false;
            #endregion
        }

        private List<t_StoreDataChangeLog> SaveChangeLog(int storeid, string assid)
        {
            // 读取变更日志
            var existingChangelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);

            Logging.GetLogger().Info("==============100===============");
            /*Egbert-取出ShortName 这条数据--2016-11-22*/
            var logshortname = existingChangelogs.Where(s => s.FieldName == "ShortName").ToList();
            /*Egbert-去除ShortName 这条数据--2016-11-22*/
            existingChangelogs = existingChangelogs.Where(c => c.FieldName != "ShortName").ToList();
            /*Egbert-显示ShortName门店昵称--2016-11-22*/
            uc_dealer1.IsShortName = logshortname.Count > 0 ? logshortname[0].ChangeReason : string.Empty;

            var store = StoreService.GetSmdStoreById(storeid) ?? new t_smd_Store();
            DataHelper<t_smd_Store>.Reload(store, existingChangelogs);
            Logging.GetLogger().Info("==============200===============");

            var newStore = store.CloneObject() as t_smd_Store;
            newStore.StoreName = AksRequest.GetFormString("tb_store_name");
            newStore.StoreStatus = ddl_StoreStatus.SelectedValue;
            newStore.StoreType = storeType.SelectedValue;
            newStore.ContactPerson = tb_ContractPerson.Text;
            newStore.PhoneNumber = tb_Telephone.Text;
            newStore.StoreSize = Utils.StrToDecimal(tb_StoreSize.Text, 0);
            newStore.ShowInWebsite = cb_ShowInWebsite.Checked;
            newStore.Region = tb_region.Text;
            newStore.Province = tb_province.Text;
            newStore.CityName = ddl_cityName.SelectedValue;
            newStore.StoreAddress = Distinct(AksRequest.GetFormString("tb_address"));
            newStore.Lon = Utils.StrToDecimal(tb_lon.Text, 0);
            newStore.Lat = Utils.StrToDecimal(tb_lat.Text, 0);
            newStore.IsColourService = cb_IsColourService.Checked;
            newStore.IsTintingService = cb_IsTintingService.Checked;
            newStore.Channel = ddl_channel.SelectedValue;
            newStore.IsUpgraded = cb_IsUpgraded.Checked;
            newStore.IsDowngraded = cb_IsDowngraded.Checked;
            newStore.IsRenew = cb_IsRenew.Checked;
            newStore.BeforeUpgradedType = ddl_BeforeUpgradedType.SelectedValue;
            newStore.BeforeDowngradedType = ddl_BeforeDowngradedType.SelectedValue;
            newStore.BeforeRenewType = ddl_BeforeRenewType.SelectedValue;
            newStore.LastRenewDate = Utils.StrToDateTimeN(tb_LastRenewDate.Text);
            newStore.OpenBusinessDate = Utils.StrToDateTimeN(tb_OpenBusinessDate.Text);
            newStore.MallShortName = tb_MallShortName.Text;
            newStore.MallName = tb_MallName.Text;
            newStore.HouseNumber = tb_HouseNumber.Text;
            newStore.ShopSeq = ddl_ShopSeq.SelectedValue;
            newStore.FirstStartDate = Utils.StrToDateTimeN(FirstStartDate.Text);
            newStore.CurrentStartDate = Utils.StrToDateTimeN(tb_CurrentStartDate.Text);
            newStore.StoreApprovedDate = Utils.StrToDateTimeN(tb_StoreApprovedDate.Text);
            newStore.EapproveSN = tb_EapproveSN.Text;
            newStore.NewFitment = l_NewFitment.Text;
            //newStore.DealerShortName = uc_dealer1.IsShortName;//chris wang

            //还有分销商信息如何处理
            #region Add By Tony 20160525

            var subdealer = new t_smd_Dealer();
            if (!string.IsNullOrEmpty(subdealercode.Text))
            {
                subdealer = DealerService.GetByCode(subdealercode.Text);
                if (subdealer != null)
                {
                    newStore.SubDealerCode = subdealer.DealerCode;
                    newStore.SubDealerName = subdealer.Name == null ? "" : subdealer.Name;
                }

            }

            //newStore.SubDealerId = string.IsNullOrEmpty(tb_subdealercode.Text) ? "" : DealerService.GetByCode(tb_subdealercode.Text).DealerID;
            if (!string.IsNullOrEmpty(bmccode.Text))
            {
                var bmc = BMCService.GetByCode(bmccode.Text);
                if (bmc != null)
                {
                    newStore.BMCCode = bmc.BMCCode;
                    newStore.BMCName = bmc.BMCName;
                }
            }

            newStore.AccountOwner = h_windowsid.Value;

            newStore.WechatId = tb_wechatid.Text;
            newStore.District = tb_District.Text;
            #endregion

            var changelogs = DataHelper<t_smd_Store>.GetChangeLogs(store, newStore,
                newStore.GetChangeFields(), "StoreID", UserAPI.UserFullName, assid, "ChangeStore", string.IsNullOrWhiteSpace(uc_dealer1.ShortName) == true ? "" : uc_dealer1.ShortName);

            // 排除前几步已修改的数据

            return ChangeLogService.GetDistinctChangeLogs(changelogs, existingChangelogs);
        }


        #region 去除重复数据
        /// <summary>
        /// 去除重复数据
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string Distinct(string content)
        /*{
            Regex ex = new Regex("(?s)(.)(?=.*\\1)");
            char[] arr = content.ToCharArray();
            Array.Reverse(arr);
            content = new string(arr);
            content = ex.Replace(content, "");
            arr = content.ToCharArray();
            Array.Reverse(arr);
            content = new string(arr);
            return content;
        }*/
        {
            string[] a = { "上海市上海市", "北京市北京市", "重庆市重庆市", "天津市天津市" };
            string[] b = { "上海上海", "北京北京", "天津天津", "重庆重庆" };
            int i =0;
            for (i = 0; i < 4; i++)
            {
                if (content.Contains(a[i]))
                {
                    content = content.Replace(content, content.Substring(3));
                }
                else if (content.Contains(b[i]))
                {
                    content = content.Replace(content, content.Substring(2));
                    i++;
                }

            }
            return content;
           
        }
        #endregion
    }
}